// Copyright (C) 2024 Kumo inc.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

#include <ktest/ktest.h>
#include <kthread/internal/countdown_event.h>
#include <atomic>
#include <turbo/times/time.h>

namespace {
    struct Arg {
        kthread::CountdownEvent event;
        std::atomic<int> num_sig;
    };

    void *signaler(void *arg) {
        Arg *a = (Arg *) arg;
        a->num_sig.fetch_sub(1, std::memory_order_relaxed);
        a->event.signal();
        return nullptr;
    }

    TEST(CountdonwEventTest, sanity) {
        for (int n = 1; n < 10; ++n) {
            Arg a;
            a.num_sig = n;
            a.event.reset(n);
            for (int i = 0; i < n; ++i) {
                kthread_t tid;
                ASSERT_EQ(0, kthread_start_urgent(&tid, nullptr, signaler, &a));
            }
            a.event.wait();
            ASSERT_EQ(0, a.num_sig.load(std::memory_order_relaxed));
        }
    }

    TEST(CountdonwEventTest, timed_wait) {
        kthread::CountdownEvent event;
        int rc = event.timed_wait(turbo::Time::to_timespec(turbo::Time::future_time(turbo::Duration::microseconds(100))));
        ASSERT_EQ(rc, ETIMEDOUT);
        event.signal();
        rc = event.timed_wait(turbo::Time::to_timespec(turbo::Time::future_time(turbo::Duration::microseconds(100))));
        ASSERT_EQ(rc, 0);
        kthread::CountdownEvent event1;
        event1.signal();
        rc = event.timed_wait(turbo::Time::to_timespec(turbo::Time::future_time(turbo::Duration::milliseconds(1))));
        ASSERT_EQ(rc, 0);
    }
} // namespace
